local root = getRootElement()
local version = "8.0 Alpha"
local PlayerAuted = {}
local PlayerLevel = {}
local PlayerTimer = {}
local node = xmlLoadFile("test.xml")

setTimer(
	function()
		time = getRealTime()
		hour = time.hour
		minute = time.minute
		second = time.second
		day = time.monthday
		month = (time.month + 1)
		year = string.sub(time.year, 2)
	end, 500, 0
)

addCommandHandler("cursor",
	function(playerid)
		if (isCursorShowing(playerid)) then
			outputChatBox("je ziet de cursor", playerid)
		else
			outputChatBox("cursor is weg", playerid)
		end
	end
)

--[[
	-----------------------------------------------------------------------
	SERVER SIDE EVENTS
	-----------------------------------------------------------------------
]]--

addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), 
    function()
		for playerKey, playerid in ipairs(getElementsByType("player")) do
			destroyPlayerSession(playerid)
			destroyPlayerBlip(playerid)
		end
    end
)
addEventHandler("onResourceStart", getResourceRootElement(getThisResource()),
	-- Resource load event
	function()
		-- setFPSLimit (100)
		setMapName("GreenHood")
		setGameType("GreenHood")
		
		-- Mass respawn
		for playerKey, playerid in ipairs(getElementsByType("player")) do
			destroyPlayerSession(playerid)
			setCameraMode(playerid, "player")
			startIntro(playerid, playerid)
		end
		
		rmsmautania = createObject(10230, -1140.8, 633.944, 6.96875, 180, 180, 90)
		rmsmautania1 = createObject(10231, -1142.31, 634.858, 8.45312, 180, 180, 90)
		rmsmautania2 = createObject(10229, -1142.21, 634.17, 5.82031, 180, 180, 90)
		rmsmautania3 = createObject(10140, -1141.85, 619.224, 7.125, 180, 180, 90)
		rmsmautania4 = createObject(10227, -1141.03, 589.041, 12.0234, 180, 180, 90)
		rmsmautania5 = createObject(10226, -1140.03, 589.57, 6.21094, 180, 180, 90)
	end
)
-- setPlayerNametagColor ( player thePlayer, int r, int g, int b )

addEventHandler("onPlayerQuit", root,
	-- Join event
	function()
		destroyPlayerSession(source)
	end
)

addEventHandler("onPlayerJoin", root,
	-- Quit event
	function(player)		
		destroyPlayerSession(source)
		outputChatBox("Welcome "..getClientName(source).."!", source)
		startIntro(source, player)
	end
)

addEventHandler("onPlayerWasted", root,
	-- Died event
	function()
		fadeCamera(source, false, 3.0, 255, 0, 0)
		setTimer(playerSpawn, 3000, 1, source)
		destroyPlayerBlip(source)
	end
)

addEventHandler("onPlayerChat", root,
	-- Chat event
	function(message, messtype)
		if messtype == 0 then
	        cancelEvent()
			message = string.gsub(message, "#%x%x%x%x%x%x", "")
			
			local level
			if PlayerLevel[source] == "500" then
				level = "~"
			elseif PlayerLevel[source] == "255" then
				level = "&"
			elseif PlayerLevel[source] == "200" then
				level = "@"
			elseif PlayerLevel[source] == "100" then
				level = "%"
			elseif PlayerLevel[source] == "10" then
				level = "+"
			else
				level = "?"
			end
			outputChatBox(string.format("[%02d:%02d:%02d] <"..level..""..string.gsub(getClientName(source), "#%x%x%x%x%x%x", "").."> "..message, hour, minute, second), root)
		end
	end
)

--[[
	-----------------------------------------------------------------------
	Events
	-----------------------------------------------------------------------
]]--

addEvent("checkAccount", true)
addEventHandler("checkAccount", root,
	function(username, password)
		if client ~= nil then
			if getAccount(getClientName(client)) then
				local loginstatus = logIn(client, getAccount(username), password)
				if loginstatus then
					local playerAccount = getClientAccount(client)
					if playerAccount then
						setPlayerMoney(client, getAccountData(playerAccount, "greenhood.money"))
						
						-- Succes
						PlayerAuted[client] = true;
						PlayerLevel[client] = getAccountData(playerAccount, "greenhood.level")
						outputChatBox("#FF0000-NickServ- Password accepted - you are now recognized.", client, 0, 0, 0, true)
						outputChatBox("#FF0000-NickServ- "..getClientName(client).." is now recognized! (level: "..PlayerLevel[client]..")", root, 0, 0, 0, true)
						triggerClientEvent(client, "hideLoginScreen", root, client)
						playerSpawn(client)
						setAccountData(playerAccount, "greenhood.lastlogin", string.format("%02d-%02d-20%02d %02d:%02d:%02d", day, month, year, hour, minute, second))
					end
				else
					outputChatBox("-NickServ- Failed to login!", client)
				end
			end
		end
	end
)

addEvent("checkRegister", true)
addEventHandler("checkRegister", root,
	function(username, password, email)
		if string.len(password) <= 5 and client ~= nil then
			outputChatBox("-NickServ- Your password must be at least 5 characters long!", client)
		elseif email == "" then
			outputChatBox("-NickServ- Type a email, it's just for you.. to get your password!!", client)
		else
		    local accountAdded = addAccount(getClientName(client), password)
            if accountAdded then
                outputChatBox("-NickServ- Thank you "..getClientName(client)..", you're now registed.", client)
				local loginstatus = logIn(client, getAccount(username), password)
				if loginstatus then
					local playerAccount = getClientAccount(client)
					if playerAccount then
						setAccountData(playerAccount, "greenhood.money", "1250")
						setAccountData(playerAccount, "greenhood.level", "10")
						setAccountData(playerAccount, "greenhood.died", "0")
						setAccountData(playerAccount, "greenhood.skin", "102")
						setAccountData(playerAccount, "greenhood.ip", getClientIP(client))
						setAccountData(playerAccount, "greenhood.usersince", string.format("%02d-%02d-20%02d %02d:%02d:%02d", day, month, year, hour, minute, second))
						setAccountData(playerAccount, "greenhood.lastlogin", string.format("%02d-%02d-20%02d %02d:%02d:%02d", day, month, year, hour, minute, second))
						setAccountData(playerAccount, "greenhood.email", email)
						
						PlayerAuted[client] = true;
						PlayerLevel[client] = 10;
						outputChatBox("#FF0000-NickServ- Password accepted - you are now recognized.", client, 0, 0, 0, true)
						outputChatBox("#FF0000-NickServ- "..getClientName(client).." is now recognized! (level: "..PlayerLevel[client]..")", root, 0, 0, 0, true)
						triggerClientEvent(client, "hideRegisterScreen", root, client)
						playerSpawn(client)
					end
				else
					outputChatBox("-NickServ- Unable to login, try: /reconnect", client)
				end
            else
                outputChatBox("-NickServ- Error creating account, contact the server admin (Error code: REG_001)!", client)
            end
		end
	end
)

--[[
	-----------------------------------------------------------------------
	FUNCTIONS
	-----------------------------------------------------------------------
]]--

function startIntro(playerid, playervalue)
	if playerid ~= nil then
		PlayerAuted[playerid] = false
		
		fadeCamera(playerid, true)
		setCameraMode(playerid, "fixed")
        setTimer(setCameraPosition, 1000, 1, playerid, -2545.2456, 1331.9952, 320)
        setTimer(setCameraLookAt, 1000, 1, playerid, -2661.7104, 1594.2255, 200.7578)
		PlayerTimer[playerid] = setTimer(cameraShow, 9000, 0, playerid)
		
		local welcomeText = textCreateDisplay()
		textDisplayAddObserver(welcomeText, playerid)
		local textMessage = textCreateTextItem("Welcome "..getClientName(playerid).."!\nGreenHood version: "..version.."!", 0.5, 0.5, "medium", 210, 182, 19, 255, 4, "center", "center")
		textDisplayAddText(welcomeText, textMessage)
		
		setTimer(textDisplayRemoveText, 7500, 1, welcomeText, textMessage)
		setTimer(loginFunc, 2000, 1, playerid, playervalue)
	end
end

function cameraShow(playerid)
	if playerid ~= nil and playerid ~= "" and PlayerTimer[playerid] ~= nil then
		local camera = randInt(5, 13)
		fadeCamera(playerid, false, 1.0)
		setTimer(fadeCamera, 1500, 1, playerid, true, 1.0)

		if camera == 5 then
			-- LS Beach
			setTimer(setCameraPosition, 1100, 1, playerid, 160.15, -1951.68, 50)
	        setTimer(setCameraLookAt, 1100, 1, playerid, 165, -1951.68, 50)
		end
		if camera == 6 then
			-- LS Airport
			setTimer(setCameraPosition, 1100, 1, playerid, 1728.1367, -2319.5529, 13.3828)
	        setTimer(setCameraLookAt, 1100, 1, playerid, 1612.0087, -2256.2788, 93.2727)
		end
		if camera == 7 then
			-- Groove street
			setTimer(setCameraPosition, 1100, 1, playerid, 2442.4499, -1648.3278, 30.5842)
	        setTimer(setCameraLookAt, 1100, 1, playerid, 2500.0307, -1673.5734, 13.3492)
		end
		if camera == 8 then
			-- SF Bridge
			setTimer(setCameraPosition, 1100, 1, playerid, -2545.2456, 1331.9952, 320)
	        setTimer(setCameraLookAt, 1100, 1, playerid, -2661.7104, 1594.2255, 200.7578)
		end
		if camera == 9 then
			-- LS Skate park
			setTimer(setCameraPosition, 1100, 1, playerid, 1835.5064, -1427.9366, 40.9218)
	        setTimer(setCameraLookAt, 1100, 1, playerid, 1912.4997, -1409.0292, 15.5703)
		end
		if camera == 10 then
			-- LS Skate park
			setTimer(setCameraPosition, 1100, 1, playerid, 2203.7399, 862.0350, 86.1167)
	        setTimer(setCameraLookAt, 1100, 1, playerid, 2028.3239, 1005.1932, 20.4707)
		end
		if camera == 11 then
			-- RMS
			setTimer(setCameraPosition, 1100, 1, playerid, -1056.4627, 716.9229, 57.3235)
	        setTimer(setCameraLookAt, 1100, 1, playerid, -1141.7897, 638.7678, 11.8084)
		end
		if camera == 12 then
			-- SF Wang cars
			setTimer(setCameraPosition, 1100, 1, playerid, -2017.3845, 285.7436, 33.9742)
	        setTimer(setCameraLookAt, 1100, 1, playerid, -1972.1691, 282.8937, 35.1718)
		end
		if camera == 13 then
			-- SF WTC
			setTimer(setCameraPosition, 1100, 1, playerid, -1831.4503, 553.9409, 240.8878)
	        setTimer(setCameraLookAt, 1100, 1, playerid, -1919.2641, 453.3290, 106.4978)
		end
	end
end

function playerSpawn(playerid)
	if playerid ~= nil then
		if PlayerTimer[playerid] ~= nil then
			killTimer(PlayerTimer[playerid])
			PlayerTimer[playerid] = nil
		end
		
		fadeCamera(playerid, true)
		setCameraMode(playerid, "player")
		createPlayerBlip(playerid)
		
		local playerAccount = getClientAccount(playerid)
		if playerAccount and PlayerAuted[playerid] then
			spawnPlayer(playerid, 1685.4743, -2240.1838, -2.6999, 180, getAccountData(playerAccount, "greenhood.skin"), 0, 0)
		end
	end
end

function loginFunc(playerid, player)
	if playerid ~= nil then
		if getClientAccount(player) then
		--if getAccount(getClientName(playerid)) then
			triggerClientEvent(playerid, "toggleLoginScreen", root, playerid)
	    else
			triggerClientEvent(playerid, "toggleRegisterScreen", root, playerid)
	    end
	end
end

function createPlayerBlip(playerid)
	if playerid ~= nil and playerid ~= "" then
		createBlipAttachedTo(playerid, 0, 2, 12, 255, 7, 180, 0, root)
	end
end

function destroyPlayerBlip(playerid)
	if playerid ~= nil and playerid ~= "" then
		local attached = getAttachedElements(playerid)
		if attached then
			for k,element in ipairs(attached) do
				if element and element ~= "" then
					if getElementType(element) == "blip" then
						destroyElement(element)
					end
				end
			end
		end
	end
end

function destroyPlayerSession(playerid)
	if PlayerAuted[playerid] then
		logOut(playerid)
	end
	if PlayerTimer[playerid] ~= nil then
		killTimer(PlayerTimer[playerid])
	end
	PlayerLevel[playerid] = 0
	PlayerAuted[playerid] = false
	PlayerTimer[playerid] = nil
	destroyPlayerBlip(playerid)
end

--[[
	-----------------------------------------------------------------------
	COMMANDS
	-----------------------------------------------------------------------
]]--

addCommandHandler("setlevel",
	function(playerid, command, param, level)
		if PlayerAuted[playerid] then
			local playerAccount = getClientAccount(getPlayerFromNick(param))
			if playerAccount then
				setAccountData(playerAccount, "greenhood.level", level)
			else
				outputChatBox("-OperServ- User doesn't exists!", playerid)
			end
		end
	end
)

addCommandHandler("skin",
	function(playerid, command, param)
		if PlayerAuted[playerid] then
			local playerAccount = getClientAccount(playerid)
			if playerAccount then
				if setPlayerSkin(playerid, param) then
					setAccountData(playerAccount, "greenhood.skin", param)
				else
					outputChatBox("-NickServ- Skin not found!", playerid)
				end
			else
				outputChatBox("-OperServ- User doesn't exists!", playerid)
			end
		end
	end
)

addCommandHandler("kill",
	function(playerid)
		killPlayer(playerid)
	end
)

addCommandHandler("timee",
	function(playerid)
		outputChatBox(string.format("%02d-%02d-20%02d %02d:%02d:%02d", day, month, year, hour, minute, second), playerid)
	end
)

addCommandHandler("lol",
	function()
		setTime(8, 30)
	end
)

addCommandHandler("xml",
	function(playerid)
		local playername = string.lower(getClientName(playerid))
		local accountName = getElementsByType(playername)
		local randomAccount = randInt(1, #accountName)
		local fetchAccount = accountName[randomAccount]
		
		if accountName then
			outputChatBox(getElementData(getElementsByType("sebas"), "skin"), playerid)
		end
	end
)

addCommandHandler("pos",
	function(playerid)
		local x, y, z = getElementPosition(playerid)
		outputChatBox("POSITION: "..x..", "..y..", "..z, playerid)
	end
)

addCommandHandler("jp",
	function(playerid)
	   if not doesPlayerHaveJetPack(playerid) then
	      local status = givePlayerJetPack(playerid)
	      if not status then
	         outputConsole("Failed to give jetpack.", playerid)
	      end
	   else
	      local status = removePlayerJetPack(playerid)
	      if not status then
	         outputConsole("Failed to remove jetpack.", playerid)
	      end
	   end
	end
)

addCommandHandler("rms",
	function(playerid)
	    setElementPosition(playerid, -1129.43, 659.499, 2.00216)
	end
)


addCommandHandler("zink3",
	function()
		moveObject(rmsmautania, 600000, -1140.8, 633.944, -64.0312, 0, 70, 0)
		moveObject(rmsmautania1, 600000, -1142.31, 634.858, -62.5469, 0, 70, 0)
		moveObject(rmsmautania2, 600000, -1142.21, 634.17, -65.1797, 0, 70, 0)
		moveObject(rmsmautania3, 600000, -1141.85, 619.224, -63.875, 0, 70, 0)
		moveObject(rmsmautania4, 600000, -1141.03, 589.041, -58.9766, 0, 70, 0)
		moveObject(rmsmautania5, 600000, -1140.03, 589.57, -64.7891, 0, 70, 0)
	end
)

addCommandHandler("terug3",	
	function()
	   	moveObject(rmsmautania, 1000, -1140.8, 633.944, 6.96875, 0, -70, 0)
	   	moveObject(rmsmautania1, 1000, -1142.31, 634.858, 8.45312, 0, -70, 0)
	   	moveObject(rmsmautania2, 1000, -1142.21, 634.17, 5.82031, 0, -70, 0)
		moveObject(rmsmautania3, 1000, -1141.85, 619.224, 7.125, 0, -70, 0)
		moveObject(rmsmautania4, 1000, -1141.03, 589.041, 12.0234, 0, -70, 0)
		moveObject(rmsmautania5, 1000, -1140.03, 589.57, 6.21094, 0, -70, 0)
	end
)



local distance = 5 --units
-- define our handler (we'll take a variable number of parameters where the name goes, because there are vehicle names with more than one word)
function consoleCreateVehicle ( sourcePlayer, commandName, ... )
   -- if a player triggered it, not the admin,
   if ( sourcePlayer ) then
      -- calculate the position of the vehicle based on the player's position and rotation:
      local x, y, z = getElementPosition ( sourcePlayer ) -- get the player's position
      local rotZ = getPlayerRotation ( sourcePlayer ) -- get the player's rotation around the Z axis in degrees
      x = x + ( ( math.cos ( math.rad ( rotZ ) ) ) * distance ) -- calculate the X position of the vehicle
      y = y + ( ( math.sin ( math.rad ( rotZ ) ) ) * distance ) -- calculate the Y position of the vehicle

      -- get the complete vehicle name by joining all passed parameters using Lua function table.concat
      local vehicleName = table.concat({...}, " ")
      -- get the vehicle's model ID from the name
      local vehicleID = getVehicleIDFromName ( vehicleName )
      -- if vehicle ID is valid,
      if vehicleID then
            -- create the vehicle using the information gathered above:
            local newVehicle = createVehicle ( vehicleID, x, y, z, 0, 0, rotZ )
            -- if vehicle creation failed, give the player a message
            if ( newVehicle == false ) then
               outputConsole ( "Failed to create vehicle.", sourcePlayer )
            end
			warpPlayerIntoVehicle(sourcePlayer, newVehicle)
      end
   end
end

addCommandHandler ( "v", consoleCreateVehicle )
